package Q5;

import Q4.Client;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.net.SocketException;

public class ClientRead implements Runnable {

    private Socket socket;
    private String username;

    public ClientRead(Socket socket, String username) {
        this.socket = socket;
        this.username = username;
    }

    @Override
    public void run() {
        BufferedReader br = null;
        try {
            br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            while(true) {
                String msg = br.readLine();
                if (null == msg) {
                    break;
                }
                if ("file".equalsIgnoreCase(msg)) {
                    String fileName = br.readLine();
                    if ("fail".equalsIgnoreCase(fileName)) {
                        System.out.println("文件不存在");
                    } else {
                        ClientTool.recieveFileFromServer (socket, new File("D:/Talk/client/" + username + fileName));
                    }
                } else {
                    System.out.println(msg);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (br != null) {
                    br.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
